# -*- coding: utf-8 -*-
# @Time    : 2024/4/16 19:07
# @Author  : Alvin
# @File    : CheUtil.py
# @Des     :
import json
import random
import re
import time
from datetime import datetime

# 获取cookie
from constants import Constants
from model.GetNumParam import GetNumParam
from utils import BussinessUtil


def get_request_header(token, requestToken):
    header = {
        "accept": "*/*",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/json; charset=UTF-8",
        "hango-origin": "lanqiao",
        "lqgraytmscode": "78210",
        "lqgrayversion": "1.5.9",
        "origin": "https://t9bs.lqfast.com",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://t9bs.lqfast.com/",
        "requesttoken": requestToken,
        "sec-ch-ua": "\"Google Chrome\";v=\"137\", \"Chromium\";v=\"137\", \"Not/A)Brand\";v=\"24\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-site",
        "tenantcode": "78210",
        "token": token,
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
    }
    return header


def get_param_u(token):
    """
    获取参数中的u，用户信息，固定值
    :param token:
    :return:
    """
    u = {
        "token": token,
        "tmsCode": "78210",
        "userId": "优斯雅通达",
        "userName": "优斯雅通达",
        "loginSite": "优斯雅通达",
        "tmsbshxsite": "优斯雅通达",
        "browserId": None,
        "loginSiteCode": "20",
        "tmsbsgsname": "佛山市晋良物流有限公司"
    }
    return u


def generate_random_digits(length):
    # 生成一个由随机数字组成的字符串
    random_digits = ''.join(random.choices('0123456789', k=length))
    return random_digits


# 获取收件人信息
def getReceiverInfo(receiverName, receiverPhone, receiverAddressDetail):
    if "*" in receiverPhone:
        receiverPhone = Constants.default_tel
    if "*" in receiverAddressDetail:
        receiverAddressDetail = receiverAddressDetail.replace("*", "")
    cha = 11 - len(receiverPhone)
    if cha != 0:
        receiverPhone = receiverPhone + generate_random_digits(cha)
    param = {
        "receiver": receiverName,
        "receiverMobile": receiverPhone,
        "endDetail": receiverAddressDetail
    }
    return param


# 获取商品信息，数量默认为1
def getGoodsInfo(goodsTitle):
    if not goodsTitle:
        goodsTitle = "美妙的商品"
    goodsInfo = {
        "name": goodsTitle,
        "num": "1"
    }
    return goodsInfo


def get_good_list(goods_name, goodsCount):
    goods_list = [
        {
            "product": goods_name,
            "qty": goodsCount,
            "weight": None,
            "volumn": None,
            "guige": None,
            "cangwei": None,
            "package": Constants.package_type,
            "vprice": 0,
            "wprice": 0,
            "qtyprice": 0,
            "acctrans": None,
            "acchuikou_xf": None,
            "acchuikou_qf": None,
            "accdaishou": None,
            "accsend": None,
            "accdeclare": None,
            "accsafe": None,
            "accsrjincang": None,
            "accduantu": None,
            "accpackage": None,
            "accfactduantu": None,
            "acccc": None,
            "hksxf": None,
            "acczx": None,
            "accsaferate": "3",
            "accdaidian": None,
            "acczz_xf": None,
            "acczz_qf": None,
            "accbaoguan": None,
            "acctax": None,
            "weight_c": None,
            "volumn_c": None,
            "accsend_c": None,
            "outacc_c": None,
            "outacc": 0,
            "singleweight": 0,
            "singlevolumn": 0
        }
    ]
    return goods_list


def get_create_order_param(token, save_billing_token, mailNo_self, goods_list, param: GetNumParam, receiverInfo):
    """
    获取创建订单参数
    :param token:
    :param save_billing_token:
    :param mailNo_self: 不包含前缀的单号
    :param goods_list:
    :param param:
    :param receiverInfo:
    :return:
    """
    receiverName = receiverInfo.get("receiver")
    receiverMobile = receiverInfo.get("receiverMobile")
    endDetail = receiverInfo.get("endDetail")
    receive_add_detail = f"{param.receiveProvince}{param.receiverCity}{param.receiverRegion}{endDetail}"
    data = {
        "m": "func",
        "n": "saveBilling",
        "p": {
            "isOnlyPrint": "",
            "unit_1": mailNo_self,
            "billno_2": mailNo_self,
            "billdate_3": BussinessUtil.get_current_format_time(),
            "bsite_4": "优斯雅通达",  # 发站
            "dailibsite": "",
            "esite_5": param.receiverCity,  # 到站
            "middlesite_6": "",
            "okprocess_7": "三包自提",  # 交接方式
            "taketype": "",
            "backqty_8": "",
            "shippercompany_9": "",
            "shipper_10": param.senderName,  # 发货人
            "shippertel_11": "",
            "shippermb_12": param.senderPhone,  # 发货电话
            "consigneecompany_13": "",
            "consignee_14": receiverName,  # 收件人
            "consigneetel_15": "",
            "consigneemb_16": receiverMobile,  # 收件电话
            "product_17": param.goodsTitle,  # 商品名称
            "qty_18": param.goodsCount,  # 商品数量
            "remainqty_19": 1,
            "package_20": Constants.package_type,  # 包装方式
            "weight_21": 0,
            "volumn_22": 0,
            "guige": None,
            "cangwei": None,
            "acctrans_23": 0,
            "acctransbili": 0,
            "acctransdiscount": "0",
            "accsafe_24": 0,
            "accsend_25": 0,
            "acczz_xf_26": 0,
            "acczz_qf_26": 0,
            "accfetch_27": 0,
            "accdaishou_28": 0,
            "accdaidian_29": 0,
            "accnow_30": 0,
            "accarrived_31": 0,
            "accback_32": 0,
            "accmonth_33": 0,
            "acchuokuankou_34": 0,
            "acchuikou_xf_35": 0,
            "acchuikou_qf_35": 0,
            "acctype_36": "月结",
            "isdupproduct_37": 0,
            "yewuyuan_38": "",
            "createby_39": "优斯雅通达",
            "state_78": 0,
            "remark_79": "",
            "transneed_80": "普通汽运",
            "webid_81": "优斯雅通达",
            "accdeclare": 0,
            "accsaferate": "3",
            "address": "",
            "ismodify": 0,
            "billtype": 1,
            "localremark": "",
            "accpackage": None,
            "accfactduantu": None,
            "billsendtype": "",
            "hksxf": None,
            "saddr": param.sendAddressDetail,
            "xfqiantiao": 0,
            "hkyifan": 1,
            "dfyifan": 0,
            "wprice": 0,
            "vprice": 0,
            "fetchvehicleno": "",
            "fetchchauffer": "",
            "acccc": None,
            "acczx": None,
            "line": "",
            "bdqita": "",
            "bdqitaremark": "",
            "accbaoguan": 0,
            "acctax": 0,
            "weight_c": None,
            "volumn_c": None,
            "accsend_c": None,
            "outacc_c": None,
            "bankcode": "",
            "bankname": "",
            "bankman": "",
            "accsrjincang": 0,
            "accsrjincangsite": "",
            "productstr": "",
            "kdunitstr": "",
            "packagestr": "",
            "qtystr": "",
            "weightstr": "",
            "volumnstr": "",
            "guigestr": "",
            "cangweistr": "",
            "accdeclarestr": "",
            "accsafestr": "",
            "wpricestr": "",
            "vpricestr": "",
            "acctransstr": "",
            "vipno": "",
            "accsafeout": 0,
            "modifiedman": "",
            "shipperId": "",
            "qtyprice": 0,
            "qtypricestr": "",
            "dfweifu": 0,
            "sheng": "",
            "city": "",
            "area": "",
            "town": "",
            "addr": receive_add_detail,  # 收件人详细地址
            "lng": "",
            "lat": "",
            "isagent": 0,
            "tydorderno": "",
            "ssheng": "",
            "scity": "",
            "sarea": "",
            "stown": "",
            "saddress": "",
            "gbsite": "",
            "zxb_orderid": "",
            "source": "",
            "outcygs": "",
            "carrierNetDot": "",
            "inroadcondition": "",
            "arrive": "",
            "vehiclearrived": "",
            "outcompanyid": "",
            "volumninfo": "",
            "volumninfostr": "",
            "weightinfo": "",
            "weightinfostr": "",
            "keyid": "",
            "companyCOID": "",
            "account": 0,
            "wttxbxfkfs": -1,
            "InputType": "电脑开单",
            "billno_old": "",
            "inunitparm": "0",
            "acctotal": "0",
            "modifyremark": "",
            "gridJson": json.dumps(goods_list),
            "oldCargo": "[]",
            "oldunit": "",
            "sendkm": "",
            "accsend_wt": "",
            "danyuanhao": "",
            "issendsms": 0,
            "billnonum": "",
            "isKZ": "",
            "printtyd": 0,
            "printlabel": 0,
            "printenv": 0,
            "printdaishou": 0,
            "cardaddress": "",
            "dateOfBirth": "",
            "effectiveDate": "",
            "expireDate": "",
            "gender": "",
            "idCardNo": "",
            "issueAt": "",
            "cardname": "",
            "nation": "",
            "picture": "",
            "isBillnoState": 0,
            "ksbq_id": "0",
            "wid_class": "",
            "wid_type": "0",
            "widStr": "0",
            "wid_DetailStr": "0",
            "wid_orderStr": "0",
            "shipperno": "",
            "shippername": "",
            "innerQty": "",
            "consigneeidno": "",
            "prescription": "",
            "outacc": 0,
            "isnoprinthuikou": 0,
            "zxgroup": "",
            "isnoprintacctrans": 0,
            "acctrans_c": 0,
            "cb_acccz": 0,
            "accsend_c77335": 0,
            "accsend_s77335": 0,
            "outacc_c77335": 0,
            "ratiotype": "",
            "singleweight": 0,
            "singlevolumn": 0,
            "singleweightstr": "",
            "singlevolumnstr": "",
            "is_only_sb": 0,
            "sf_id": 0,
            "accsf": "",
            "accaz": "",
            "accps": "",
            "pdremark": "",
            "estimatedSendDate": "",
            "deliverytime": "",
            "defaultprinttydnum": "1",
            "defaultPrintLabelNum": "",
            "isacctax": 0,
            "cashamount": 0,
            "accsend_c82233": 0,
            "accsend_s82233": 0,
            "outacc_c82233": 0,
            "isyxj": 0,
            "accbaoguanstr": "",
            "acctaxstr": "",
            "unitgentype": "1",
            "addresseemsg": "",
            "sendermsg": "",
            "outaccNew": 0,
            "imgUrlList": "[]",
            "imgPathList": "[]",
            "xiayouunit": "",
            "xiayoutmscode": "",
            "xiayoutmsname": "",
            "saveBillingToken": save_billing_token
        },
        "l": "",
        "v": "",
        "u": {
            "token": token,
            "tmsCode": "78210",
            "userId": "优斯雅通达",
            "userName": "优斯雅通达",
            "loginSite": "优斯雅通达",
            "tmsbshxsite": "优斯雅通达",
            "browserId": None,
            "loginSiteCode": "20",
            "tmsbsgsname": "佛山市晋良物流有限公司"
        },
        "r": "k",
        "s": "k",
        "t": int(time.time() * 1000)
    }
    return data


def get_num_from_mail_no(mailNo):
    # 提取所有整数
    num_list = re.findall(r'\d+\d*', mailNo)
    if not num_list:
        return None
    return num_list[0]


def get_order_first_num(express):
    if not express:
        return 1
    if "中通" in express:
        return 2
    elif "韵达" in express:
        return 3
    elif "申通" in express:
        return 4
    elif "极兔" in express:
        return 5
    elif "邮政" in express or "EMS" in express or "ems" in express:
        return 6
    elif "圆通" in express:
        return 7
    else:
        return 8


# 根据创建车氏物流接口响应数据获取需要的内容
def getCreateOrderResult(createId, resp):
    createResult = {
        "order_num": None,
        "msg": None,
        "code": 0
    }
    if resp['errno'] == 0:
        res = resp.get("res", None)
        if not res:
            createResult['code'] = 1
            createResult['msg'] = f"【{createId}】创建订单时 res 为空，订单创建失败"
            return createResult
        order_data = res.get("order_data", None)
        if not order_data:
            createResult['code'] = 2
            createResult['msg'] = f"【{createId}】创建订单时 order_data 为空，订单创建失败"
            return createResult
        order_num = order_data.get("order_num", None)
        createResult['order_num'] = order_num
        return createResult
    else:
        createResult['code'] = 3
        createResult['msg'] = f"【{createId}】创建订单失败：{resp['errmsg']}"
        return createResult


# 获取物流描述
def getLogisticsDescriptionByLogisticsItem(dbItem, updateType, context):
    """
    根据快递获取物流描述
    :param dbItem:
    :param updateType:
    :param context:
    :return:
    """
    des = context
    receiverArea = dbItem.get("receiverArea", None)
    pickingCode = dbItem.get("pickingCode", None)
    phone_numbers = re.findall(r'1\d{10}', context)
    mobile = Constants.default_tel
    if phone_numbers is not None and len(phone_numbers) > 0:
        mobile = phone_numbers[0]
    if updateType == "送货中":
        des = f"{receiverArea}网点：您的包裹正在为您派送，如有疑问请联系:{mobile},感谢您的耐心等待"
    elif updateType == '已送货':
        des = f"取件码:{pickingCode},{context}"
    elif updateType == '已签收':
        des = f"您的包裹已签收，如有疑问请联系:{mobile},期待再次为您服务！"
    if len(des) > 100:
        des = des[:99]
    return des
